package top.yangyitao.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import top.yangyitao.dto.AttendanceRecordDto;
import top.yangyitao.dto.ResultDto;
import top.yangyitao.dto.TableDto;
import top.yangyitao.dto.UserDto;
import top.yangyitao.entity.AttendanceRecord;
import top.yangyitao.entity.User;
import top.yangyitao.entityEnum.UserWorkStatusEnum;
import top.yangyitao.service.AttendanceRecordService;
import top.yangyitao.service.UserService;
import top.yangyitao.utils.DateUtil;

@RestController
public class UserAttendanceRecordController {
	@Autowired
	AttendanceRecordService userAttendanceRecordService;
	
	@Autowired
	UserService userService;
	
	@RequiresAuthentication
	@RequestMapping("/userAttendanceRecord_html")
	public ModelAndView userAttendanceRecord_html() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/userAttendanceRecord.html");
		return mv;
	}
	
	@RequiresAuthentication
	@RequestMapping("/addUserAttendanceRecord")
	public ResultDto addUserAttendanceRecord() {
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User user = userService.getOne(userDto.getId());
		if(user.getWorkStatus()!=UserWorkStatusEnum.ONWORK.getType())
			return new ResultDto("非在职人员",null,2);
		AttendanceRecord userAttendanceRecord = new AttendanceRecord();
		userAttendanceRecord.setCheckTime(DateUtil.getYYYY_MM_DD_HH_MM_Format().format(new Date()));
		userAttendanceRecord.setUser(user);
		userAttendanceRecordService.save(userAttendanceRecord);
		return new ResultDto("添加打卡记录成功",null,0);
	}

	
	@RequiresAuthentication
	@RequestMapping("/getUserAttendanceRecordPage")
	public TableDto<AttendanceRecordDto> getUserAttendanceRecordPage(Integer pageNumber,Integer pageSize,String startDay,String endDay,String search) {
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		Page<AttendanceRecord> pageResult = userAttendanceRecordService.getAttendanceRecordPage(pageNumber,pageSize,null,userDto.getId(),startDay,endDay,search);
		List<AttendanceRecord> userAttendanceRecords = pageResult.getContent();
		List<AttendanceRecordDto> userAttendanceRecordDtos = new ArrayList<AttendanceRecordDto>();
		userAttendanceRecords.forEach(userAttendanceRecord->userAttendanceRecordDtos.add(new AttendanceRecordDto().convert(userAttendanceRecord)));
		return new TableDto<AttendanceRecordDto>(userAttendanceRecordDtos,pageResult.getTotalElements());
	}
}
